import React, { useCallback } from 'react';
import { useUnifiedWalletContext, useUnifiedWallet } from '@jup-ag/wallet-adapter';
import { SolanaMobileWalletAdapterWalletName } from '@solana-mobile/wallet-adapter-mobile';
import { useWallet } from '@solana/wallet-adapter-react';
import './index.scss'

export const WalletButton = ({ size }) => {
  const { setShowModal } = useUnifiedWalletContext();
  const { connect, connecting, wallet } = useUnifiedWallet();
  const { publicKey } = useWallet();

  const handleClick = useCallback(async () => {
    try {
      if (wallet?.adapter?.name === SolanaMobileWalletAdapterWalletName) {
        await connect();
        return;
      } else {
        setShowModal(true);
      }
    } catch (error) {
      setShowModal(true);
    }
  }, [wallet, connect, setShowModal]);

  function shortenAddress(address, chars = 4) {
    return `${address.slice(0, chars)}...${address.slice(-chars)}`;
  }

  return (
    <>
      {!wallet?.adapter.connected ? (
        <div
          className={`login-btn ${size}`}
          onClick={handleClick}
        >
          {connecting ? (
            <span tw="text-xs">
              <span>Connecting...</span>
            </span>
          ) : (
            <span tw="hidden md:block">
              <span>Connect Wallet</span>
            </span>
          )}
        </div>
      ) : (
        <div className='islogin'>
          <img alt="Wallet logo" width={16} height={16} src={wallet?.adapter?.icon} />
          <div>{shortenAddress(`${publicKey}`)}</div>
          <img className='select-icon' alt="Wallet select" src={require('../../assets/down-arrow.png')} />
        </div>
      )}
    </>
  );
};